<?php
require_once ('config.php');
require_once ('databasefunctions.php');
require_once ('displayfunctions.php');
require_once ('businessfunctions.php');
//validate_user();

create_transaction();

// Summarize expenses? Can be (t)otal, for (e)xpense type or (n)one
$sumexp = $_GET['SumExp'];

// select transactions relating to that bill
$sql = "SELECT * FROM billtransaction WHERE ";
$sql .= "CompanyID = '" . $_GET['BillCompanyID'] . "' AND ";
$sql .= "BillNo = '" . $_GET['CustomNumber'] . "' AND ";
$sql .= "BillDate LIKE '" . $_GET['BillYear'] . "%' ";
$sql .= "ORDER BY TransactionDate";
$sql_result = sql_execute($sql);
$i = 0;
while ($sql_data = mysql_fetch_array($sql_result)) {
       $BillNumber = $sql_data['BillNo'];
       $BillDate = $sql_data['BillDate'];
       $amount = $sql_data['Quantity'] * $sql_data['ChargeRate'];
       $user_date = convert_mysql_date4output($sql_data['TransactionDate']);

       // Get some descriptions...
       $JobData  = mysql_fetch_array(sql_execute("select * from jobmaster where JobID='".$sql_data['JobID']."'"));
       $ChargeData = mysql_fetch_array(sql_execute("select * from chargetypemaster where ChargeID='".$sql_data['ChargeID']."'"));
       $StaffData  = mysql_fetch_array(sql_execute("select * from staffmaster where StaffID='".$sql_data['StaffID']."'"));

       $_SESSION['transaction'][$i] = array (
           'TransactionID' => $sql_data['TransactionID'],
           'CompanyID' => $sql_data['CompanyID'],
           'ClientID' => $sql_data['ClientID'],
           'JobID' => $sql_data['JobID'],
           'ChargeID' => $sql_data['ChargeID'],
           'ChargeType' => $ChargeData['ChargeType'],
           'StaffID' => $sql_data['StaffID'],
           'TransactionDate' => $sql_data['TransactionDate'],
           'FromTime' => $sql_data['FromTime'],
           'ToTime' => $sql_data['ToTime'],
           'ChargeRate' => $sql_data['ChargeRate'],
           'TaxRate' => $sql_data['TaxRate'],
           'NetRate' => $sql_data['NetRate'],
           'Quantity' => $sql_data['Quantity'],
           'Amount' => $amount,
           'Remark' => $sql_data['Remark'],
           'JobName' => $JobData['JobName'],
           'ChargeDescription' => $ChargeData['ChargeDescription'],
           'StaffName' => $StaffData['StaffName'],
           'StaffGrade' => $StaffData['StaffGrade']
       );
       $i ++;
}
// if no transaction found, return to selection screen
if (! $_SESSION['transaction']) {
      message_box($langbilllnotexist);
      echo "<script>history.go(-1)</script>";
      exit;
}

// Summarization of expense
$count = count($_SESSION['transaction']);
if ($sumexp != "n") {
    for ($i=0; $i < $count; $i++) {
        $tr = $_SESSION['transaction'][$i];
        if ($tr["ChargeType"]!="H") {
            // Summarize for expense type (ChargeID) + JobName
            if ($sumexp == "e"){
                // If that's the first expense/job of this type, create a new line and unset specific values
                $key = $tr["ChargeID"].$tr["JobName"];
                if (!isset($_SESSION['transaction'][$key])) {
                    $_SESSION['transaction'][$key] = $_SESSION['transaction'][$i];
                    unset ($_SESSION['transaction'][$key]["TransactionDate"]);
                    unset ($_SESSION['transaction'][$key]["ChargeRate"]);
                    unset ($_SESSION['transaction'][$key]["Quantity"]);
                    unset ($_SESSION['transaction'][$key]["Amount"]);
                }
                $_SESSION['transaction'][$key]["Amount"] += $tr["Amount"];
                $_SESSION['transaction'][$key]["Quantity"] += $tr["Quantity"];
            // Summarize all expenses
            } else if ($sumexp == "t"){

            }
            // Get rid of this transaction as it was summerized and thus must not be printed
            unset($_SESSION['transaction'][$i]);
        }


    }
}


print_bill($BillNumber, $BillDate);




function print_bill ($bill_number, $bill_date) {
// displaying the bill in html
        global $langinvoice, $langclientid, $langclientname, $langaddress, $langbillno, $langbilldate, $langdearsir,
                   $langjobid, $langchargeid, $langstaffid, $langtransactiondate, $langtimefrom, $langtimeto,
                   $langprice, $langqtyhour, $langamount, $langtotal, $langreference,
                   $langVAT, $langchargetype, $langstaffname, $langstaffgrade, $langjobname, $langtaxable,
                   $langduedate , $langpaymethod ,$langreference, $langgrossrate;

        // HEADER **************************************************************
        ?>
        <html>
        <head>
        <title>Custom Bill Print</title>
        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
        </head>
        <LINK REL="StyleSheet" HREF="styleprint.css" TYPE="text/css">
        <body>

        <?
        // BILL HEADER *********************************************************

        // Get bill additional data (paymethod, duedate, etc)
        $billyear = $_GET['BillYear'];
        $billcompany = $_GET['BillCompanyID'];
        $billdata = mysql_fetch_array(sql_execute("SELECT * FROM billdata WHERE CompanyID='$billcompany' AND BillNo='$bill_number' AND Year='$billyear'"));

        reset ($_SESSION['transaction']);
        $temp = current($_SESSION['transaction']);

        // get company name
        $sql = "SELECT * FROM companymaster WHERE CompanyID = '" ;
        $sql .= $temp['CompanyID'] . "'";
        $sql_result = sql_execute($sql);
        $company_data = mysql_fetch_array($sql_result);
        $companyname = $company_data['CompanyName'];
        ?>
        <div align="center">
             <img src="img/logo.png" alt="GDA Logo" border=0><br>
             <b><?echo $company_data['CompanyName']?></b>&nbsp;&nbsp;
             <?echo $company_data['additional']?>
             <hr><br><br><br><br><br>
        </div>

        <!-- CUSTOMER ********************************************************** -->
        <?
        // get client name
        $sql = "SELECT * FROM clientmaster WHERE ClientID = '" ;
        $sql .= $temp['ClientID'] . "'";
        $sql_result = sql_execute($sql);
        $sql_data = mysql_fetch_array($sql_result);
        ?>
        <table width="100%">
                <tr>    <td width="55%"> <!-- SPACER FROM LEFT -->
                        <td><? echo $langdearsir." ".$sql_data['ClientName'] ?>
                <tr>    <td>
                        <td><? echo $sql_data['Address1'] ?>
                <tr>    <td>
                        <td><? echo $sql_data['Address2'] ?>
                <tr>    <td>
                        <td><? echo $sql_data['Address3'] ?>
                <tr>    <td>
                        <td><? echo $sql_data['Address4'] ?>
        </table>
        <br>
        <table border="1">
                <tr>
                        <td><b><? echo $langbillno ?></b>
                        <td><b><? echo $bill_number ?></b>
                <tr>
                        <td><b><? echo $langbilldate ?></b>
                        <td><b><? echo convert_mysql_date4output($bill_date) ?></b>
                <tr>
                        <td><b><? echo $langduedate ?></b>
                        <td><b><? echo convert_mysql_date4output($billdata["DueDate"]) ?></b>
                <tr>
                        <td><b><? echo $langpaymethod ?></b>
                        <td><b><? echo $billdata["PayMethod"] ?></b>
                <tr>
                        <td><b><? echo $langreference ?></b>
                        <td><b><? echo $billdata["Reference"] ?></b>


        </table>
        <br>
        <!-- ITEM HEADINGS ***************************************************** -->
        <table width="100%" border="1">
        <tr bgcolor='<? echo $color1 ?>' align="center">
                <td><? echo $langjobname ?>
                <td><? echo $langchargetype ?>
                <td><? echo $langstaffname ?>
                <td><? echo $langtransactiondate ?>
                <td><? echo $langtimefrom ?>
                <td><? echo $langtimeto ?>
                <td><? echo $langprice ?>
                <td><? echo $langqtyhour ?>
                <td><? echo $langVAT ?>
                <td><? echo $langamount ?>
        <?

        // ITEMS ***************************************************************
        // list un-bill transaction
        $total_amount = 0;
        foreach ($_SESSION['transaction'] as $content) {
                $user_date = convert_mysql_date($content['TransactionDate']);
                $user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
                echo "\n<tr>";
                echo "<td>" . $content['JobName'];
                echo "<td>" . $content['ChargeDescription'];
                echo "<td>" . $content['StaffName'];
                echo "<td align='right'>" . $user_date;
                echo "<td align='right'>" . substr($content['FromTime'],0,5);
                echo "<td align='right'>" . substr($content['ToTime'],0,5);
                echo "<td align='right'>" . $content['ChargeRate'];
                echo "<td align='right'>" . $content['Quantity'];
                echo "<td align='right'>" . $content['TaxRate'] . "%";
                echo "<td align='right'>"; printf('%.2f', $content['Amount']) ;
                if ($content['NetRate']==0) {
                        echo " *";
                        $grossrateitems = true;
                }
                $total_amount += $content['Amount'];

                if (! empty($content['Remark'])) {
                        echo "\n<tr><td><td colspan='7'>" . $content['Remark'];
                }
                echo "\n<tr><td colspan='9'>";

                // Tax Calculation
                if ($content['TaxRate']!="0.00") {
                    $tax[$content['TaxRate']]['taxrate'] = $content['TaxRate'];
                    // Amount is VAT included
                    if ($content['NetRate']==0) {
                        $tax[$content['TaxRate']]['tax'] += $content['Amount'] / (100+$content['TaxRate']) * $content['TaxRate'];
                        $tax[$content['TaxRate']]['taxable'] += $content['Amount'] / (100+$content['TaxRate']) * 100;
                    // Amount is VAT excluded
                    } else {
                        $tax[$content['TaxRate']]['tax'] += $content['Amount'] / 100 * $content['TaxRate'];
                        $tax[$content['TaxRate']]['taxable'] += $content['Amount'];
                    }
                }
        }

        echo "\n";
        // BILL TOTALS *********************************************************
        if ($tax)
        foreach ($tax as $taxdetail) {
                 $taxtotal += $taxdetail["tax"];
        ?>
        <tr>
                <td align = 'right' colspan = '9'>
                    <? echo $langVAT . " " . $taxdetail['taxrate'] . "% (" . $langtaxable . " " . number_format($taxdetail['taxable'],2,'.','') . ")" ?>
                <td align = 'right'><? printf('%.2f', $taxdetail['tax']) ?>
        <? } ?>
        <tr>
                <td align = 'right' colspan = '9'><b><? echo $langtotal." ".$company_data['Currency'] ?></b>
                <td align = 'right'><b><? printf('%.2f', $total_amount+$taxtotal) ?></b>
        </table>

        <?
        if ($grossrateitems)
            echo ("* " . $langgrossrate);

        // FOOTER **************************************************************
        ?>
        </body></html>
        <?
}

























function validate_input() {
// validate user input for billing range
        global $DateFrom, $DateTo, $langinvalidclient, $langinvaliddate, $langfrom, $langto, $langinvaliddaterange;

        // if client ID is empty and action is auto, no need to check client ID
        if (! (empty($_GET['ClientID']) && $_GET['action'] == 'auto')) {
                if (! validate_client($_GET['ClientID'])) {
                        $error_text .= "<br>- $langinvalidclient<br>";
                }
        }

        $DateFrom = validate_date($_GET['FromDate'], 1);
        if (! $DateFrom) {
                $error_text .= "<br>- $langinvaliddate $langfrom<br>";
        }

        $DateTo = validate_date($_GET['ToDate'], 1);
        if (! $DateTo) {
                $error_text .= "<br>- $langinvaliddate $langto<br>";
        }

        if ($DateFrom && $DateTo & ($DateFrom > $DateTo)) {
                $error_text .= "<br>- $langinvaliddaterange<br>";
        }

        if ($error_text) {
                message_box($error_text);
                ?>
                <script>history.go(-1)</script>
                <?
                exit;
        }
}

function create_transaction() {
        // create temp session variable
        if (session_is_registered('transaction')) {
                unset ($_SESSION['transaction']);
        }
        else {
                session_register('transaction');
        }
}



?>
